var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var loginRouter = require('./routes/login');
var cors = require('cors');

//导入用于将客户端发送过来的JWT字符串解析还原成JSON对象的包
const { expressjwt: jwt } = require('express-jwt');

const config = require('./config');

var app = express();

app.use(cors());

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));




//使用 app.use() 注册将JWT字符串解析还原成JSON对象的中间件
//.unless() 方法通过正则表达式 指定哪些接口不需要通过权限
//正则中 '\'用来转义 '^'表示指定以什么开头的字符串
app.use(jwt({ secret: config.secretKey,algorithms: ['HS256'] }).unless({path: [/^\/api\//]}));
//如果出现报错 尝试在 secret: secretKey的后面加上 ", algorithms: ['HS256'] "

app.use((req, res, next) => {
  console.log("这是消息中间件")
  next()
});

app.use('/', indexRouter);
app.use('/api', loginRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
